package com.fearless.test02;

/*

    生产者消费者问题。不使用JUC的版本

 */


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//共享数据类。应该只含有属性和方法
public class Data2 {

    private int count=0;//共享变量
    Lock lock=new ReentrantLock();
    Condition condition = lock.newCondition();



   synchronized void consume()  {
       condition.signalAll();

        lock.lock();

       try {
           if(count > 0){
               System.out.println("现在库存是"+count+Thread.currentThread().getName()+"开始消费");
               count--;
           }else {
               try {
                   condition.await();
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
       }catch (Exception e){
           e.printStackTrace();
       }finally {
           lock.unlock();
       }


    }


    void produce()  {

        condition.signalAll();
        lock.lock();
            try {
                if(count==0){
                    System.out.println("现在库存是"+count+Thread.currentThread().getName()+"开始生产");
                    count++;
                }else {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }

    }


}


class Test6{
    public static void main(String[] args) {

        Data data=new Data();

        new Thread(()->{
            for (int i = 0; i <20 ; i++) {
                data.produce();
            }
        },"生产者").start();


        new Thread(()->{
            for (int i = 0; i <20 ; i++) {
                data.consume();
            }
        },"消费者").start();

    }
}